package goods

import (
	"orm_gin/model"
	"orm_gin/orm"
	"orm_gin/utools/res"
	"time"

	"github.com/gin-gonic/gin"
)

func AddGoods(c *gin.Context) {
	if has := orm.DB.Migrator().HasTable(&model.UserGoods{}); !has {
		err := orm.DB.AutoMigrate(&model.UserGoods{})
		if err != nil {
			res.Error(c, 0, err, "创建表失败")
			return
		}
	}
	// 插入数据
	var data model.UserGoods
	id, _ := c.Get("UserId")
	err := c.BindJSON(&data)
	if err != nil {
		res.Error(c, 0, err, "解析params JSON 失败")
		return
	}

	data.CreatedAt = time.Now()
	data.UpdatedAt = time.Now()
	data.UserInfoID = id.(string)
	r := orm.DB.Create(&data)

	if r.Error != nil {
		res.Error(c, 0, r.Error, "插入数据库时错误")
		return
	}

	res.Ok(c, data, "操作成功")
}
